package io.summer.basis.config;

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * @author ml
 */
@Configuration
@ConditionalOnProperty(prefix = "spring.jackson", name = {"date-format", "time-zone"})
public class DateTimeFormatConfig {
  @Value("${spring.jackson.date-format}")
  private String pattern;

  @Value("${spring.jackson.time-zone}")
  private String timeZone;

  @Bean
  public LocalDateTimeSerializer localDateTimeDeserializer() {
    return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern).withZone(ZoneId.of(timeZone)));
  }

  @Bean
  @ConditionalOnBean(LocalDateTimeSerializer.class)
  public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(LocalDateTimeSerializer serializer) {
    return builder -> builder.serializerByType(LocalDateTime.class, serializer);
  }
}
